import {createStore,applyMiddleware} from 'redux'
import list from '../mock/mock'
import Thunk from 'redux-thunk'

//mock生成的数据进行持久化
localStorage.setItem('list',JSON.stringify(list));

//点击加入收藏action
function scclick_action(item){
    return{
        type:'CLICK',
        item
    }
}

//点击取消收藏action
function cancel_action(id){
    return{
        type:'CANCEL',
        id
    }
}

//初始数据   list是存入本地的数据
var data={
    list:JSON.parse(localStorage.getItem('list')),
    sclist:[]
}

function reducer(state=data,action){

    //state=本地有数据？把本地数据转对象：state
    state=localStorage.getItem('state')?JSON.parse(localStorage.getItem('state')):state

    //深拷贝state
    state=JSON.parse(JSON.stringify(state))

    //switch循环判断
    switch(action.type){

        //触发收藏action时把点击项添加到收藏列表
        case 'CLICK':
                 state.sclist.push(action.item)

            //保存修改后的数据
            localStorage.setItem('state',JSON.stringify(state))
            return state

        //触发取消收藏action时把点击项从收藏列表生成
        case 'CANCEL':

            //找到当前项
            var findid=state.sclist.findIndex(item=> item.id===action.id)
            if(findid!==-1){

                //删除当前项
                 state.sclist.splice(findid,1)
            }
            
            //保存修改后的数据
            localStorage.setItem('state',JSON.stringify(state))
            return state
        default :
            return state
    }
}
var store=createStore(reducer,applyMiddleware(Thunk))
export{
   store ,scclick_action,cancel_action
}